package com.ymt.reliable.message.exceptionretry.timer;

import com.ymt.reliable.message.domain.TransactionMessage;
import com.ymt.reliable.message.exceptionretry.config.MessageRetryConfig;
import com.ymt.reliable.message.exceptionretry.service.MessageExceptionRetryService;
import com.ymt.reliable.message.exceptionretry.task.Task;
import com.ymt.reliable.message.exceptionretry.task.TaskFactory;
import com.ymt.reliable.message.service.TransactionMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MessageExceptionRetryTimer {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageExceptionRetryTimer.class);

    @Autowired
    private TransactionMessageService transactionMessageService;
    @Autowired
    private MessageExceptionRetryService messageExceptionRetryService;
    @Autowired
    private MessageRetryConfig retryTimesConfig;

    public void retry() {
        List<TransactionMessage> retryList = transactionMessageService.queryRetryList(retryTimesConfig.getTimeout());
        LOGGER.info(">>> 积压消息总数:{},延迟队列中任务总数:{}", retryList == null ? 0 : retryList.size(), messageExceptionRetryService.queueSize());
        if (retryList != null && retryList.size() > 0) {
            for (TransactionMessage message : retryList) {
                Task task = TaskFactory.createTask(message, retryTimesConfig);
                messageExceptionRetryService.addTask(task);
            }
        }
    }
}
